package com.brotherly.framework.app;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.telephony.TelephonyManager;
import android.webkit.WebView;

import com.brotherly.framework.service.IServiceResult;
import com.brotherly.framework.service.ServiceHost;
import com.brotherly.framework.service.ServiceManager;
import com.brotherly.mpgp.R;
import com.brotherly.mpgp.remoteinterface.User;
import com.brotherly.mpgp.service.PushService;
import com.brotherly.mpgp.util.GameManagerUtil;

public class BaseApplication extends Application implements IServiceResult
{
    public interface ApplicationReadyListener
    {
        public void onApplicationReady();
    }

    public class PackageModifyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (intent.getAction().equals(Intent.ACTION_PACKAGE_ADDED))
            {
                String packageName = intent.getDataString();
                System.out.println("安装了:" + packageName);
                isNeedReloadGameInfo = true;
            } else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED))
            {
                String packageName = intent.getDataString();
                System.out.println("重新安装了:" + packageName);
                isNeedReloadGameInfo = true;
            }
            else if (intent.getAction().equals(Intent.ACTION_PACKAGE_REMOVED))
            {
                String packageName = intent.getDataString();
                System.out.println("卸载了:" + packageName);
                isNeedReloadGameInfo = true;
            }
        }
    }

    public static final String APPKEY = "67527DFA279721A9C320AB8A7CB108853C2099D1";
    private static BaseApplication Instance;
    public static final boolean isDebugServer = false;

    public static BaseApplication getInstance()
    {
        return Instance;
    }

    private boolean isAllServiceOnReady = false;

    private boolean isMKKeyRight = true;

    private boolean isNeedReloadGameInfo = false;

    private final List<ApplicationReadyListener> mApplicationReadyListeners = new ArrayList<BaseApplication.ApplicationReadyListener>();

    private Activity mCurrentActivity;
    private JSONObject mDefaultDatas;
    private PackageModifyReceiver mPackageModifyReceiver = new PackageModifyReceiver();
    private User mUser;

    public void createUser()
    {
        User user = new User();
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = mTelephonyMgr.getSubscriberId();
        String imei = mTelephonyMgr.getDeviceId();
        WebView webview = new WebView(this);
        String userAgent = webview.getSettings().getUserAgentString();
        PackageManager pm = getPackageManager();
        PackageInfo pinfo;
        try
        {
            pinfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_CONFIGURATIONS);
            int versionCode = pinfo.versionCode;
            // String versionName = pinfo.versionName;
            user.VersionCode = versionCode;
        }
        catch (NameNotFoundException e)
        {
            e.printStackTrace();
        }

        user.IMEI = imei;
        user.IMSI = imsi;
        user.UserAgent = userAgent;
        String phoneInfo = "Product: " + android.os.Build.PRODUCT;
        phoneInfo += ", CPU_ABI: " + android.os.Build.CPU_ABI;
        phoneInfo += ", TAGS: " + android.os.Build.TAGS;
        phoneInfo += ", VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE;
        phoneInfo += ", MODEL: " + android.os.Build.MODEL;
        phoneInfo += ", VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE;
        phoneInfo += ", DEVICE: " + android.os.Build.DEVICE;
        phoneInfo += ", DISPLAY: " + android.os.Build.DISPLAY;
        phoneInfo += ", BRAND: " + android.os.Build.BRAND;
        phoneInfo += ", BOARD: " + android.os.Build.BOARD;
        phoneInfo += ", FINGERPRINT: " + android.os.Build.FINGERPRINT;
        phoneInfo += ", ID: " + android.os.Build.ID;
        phoneInfo += ", MANUFACTURER: " + android.os.Build.MANUFACTURER;
        phoneInfo += ", USER: " + android.os.Build.USER;
        user.Device = phoneInfo;
        this.mUser = user;
    }

    public Activity getCurrentActivity()
    {
        return mCurrentActivity;
    }

    public JSONObject getDefaultDatas()
    {
        return this.mDefaultDatas;
    }

    public User getUser()
    {
        return mUser;
    }

    public boolean isAllServiceOnReady()
    {
        return isAllServiceOnReady;
    }

    public boolean isMKKeyRight()
    {
        return isMKKeyRight;
    }

    public boolean isNeedReloadGameInfo()
    {
        return isNeedReloadGameInfo;
    }

    private void loadDefaultSettings()
    {
        InputStream is = null;
        try
        {
            is = getAssets().open("default.json");
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null)
            {
                sb.append(line);
            }
            mDefaultDatas = new JSONObject(sb.toString());
        }
        catch (Exception e)
        {

            e.printStackTrace();
        }
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Instance = this;
        createUser();
        ServiceManager.getInstance().setServiceResultListener(this);
        ServiceManager.getInstance().startService(this);
        loadDefaultSettings();

        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentfilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentfilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentfilter.addDataScheme("package");
        registerReceiver(mPackageModifyReceiver, intentfilter);

        Timer updateWidget = new Timer();
        updateWidget.schedule(new TimerTask()
        {

            @Override
            public void run()
            {
                Intent in = new Intent();

                in.setAction("android.appwidget.action.APPWIDGET_UPDATE");
                sendBroadcast(in);
            }
        }, 1000, 60000);

        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                // PushService.actionStart(BaseApplication.this);
            }
        }).start();
    }

    @Override
    public void onLowMemory()
    {
        super.onLowMemory();
    }

    @Override
    public void onServiceStart(ServiceHost serviceHost)
    {
        isAllServiceOnReady = true;
        ServiceManager.getInstance().removeServiceResultListener(this);
        List<ApplicationReadyListener> lisns = new ArrayList<BaseApplication.ApplicationReadyListener>(
                mApplicationReadyListeners);
        for (ApplicationReadyListener callback : lisns)
        {
            callback.onApplicationReady();
        }
    }

    @Override
    public void onTerminate()
    {
        unregisterReceiver(mPackageModifyReceiver);
        ServiceManager.getInstance().stopService(this);
        Instance = null;
        super.onTerminate();
    }

    public void registerApplicationReadyListener(ApplicationReadyListener callback)
    {
        if (!mApplicationReadyListeners.contains(callback))
        {
            mApplicationReadyListeners.add(callback);
        }
    }

    public void setCurrentActivity(Activity activity)
    {
        mCurrentActivity = activity;
    }

    public void setNeedReloadGameInfo(boolean need)
    {
        this.isNeedReloadGameInfo = need;
        if (this.isNeedReloadGameInfo)
        {
            GameManagerUtil.loadPackageInfo(this, null);
        }
    }

    public void unregisterApplicationReadyListener(ApplicationReadyListener callback)
    {
        mApplicationReadyListeners.remove(callback);
    }

    private static int APKInstallNotify = 0;
    private HashMap<String, Integer> APKNotifys = new HashMap<String, Integer>();

    @SuppressWarnings("deprecation")
    public void checkInstallApk(JSONObject json)
    {
        int filesize = json.optInt("fileSize");
        int complete = json.optInt("compelete");
        if (complete < filesize)
        {
            return;
        }
        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification();
        notification.icon = R.drawable.ic_launcher;
        notification.tickerText = json.optString("filename") + "，下载成功了";
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.defaults = Notification.DEFAULT_SOUND;
        notification.audioStreamType = android.media.AudioManager.ADJUST_LOWER;
        notification.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;

        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + json.optString("localfile")),
                "application/vnd.android.package-archive");

        // PendingIntent
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        notification.setLatestEventInfo(this, "手机游戏旋风：", "下载成功请安装", pendingIntent);
        nm.notify(++APKInstallNotify, notification);
        APKNotifys.put(json.optString("localfile"), APKInstallNotify);
    }

    public void cancelNotify(String localfile)
    {
        Integer id = APKNotifys.get(localfile);
        if (id != null)
        {
            NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nm.cancel(id);
            APKNotifys.remove(localfile);
        }
    }

}
